#!/bin/bash

#启动命令及参数
ExeName="hr"
OutPath="./_bin/"$ExeName"/"
Target="s_"$ExeName
StartComment="$OutPath$Target -logLv=0 -logMode=3"

if [ "$1" = "" ]; then
    echo -e "\033[0;31m 未输入环境参数 \033[0m  \033[0;34m {test|online|run|build} \033[0m"
    exit 1
fi

Params=(test,online,run,build)
if echo "${Params[@]}" | grep -w "$1" &>/dev/null; then
	echo ""
else
 	echo -e "\033[0;31m 错误的输入参数 \033[0m  \033[0;34m {test|online|run|build} \033[0m"
    exit 1
fi

if [ "$Target" = "" ];
then
    echo -e "\033[0;31m 未填写编译目标 \033[0m"
    exit 1
fi

cp main.$ExeName.go_ main.$ExeName.go
cp go.mod_ go.mod && go mod tidy

function do_test_env()
{
    echo -e "target:$Target\033[0;33m build... \033[0m"
    CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-w" -o $OutPath$Target main.$ExeName.go
	# CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-w -s -X main.Version=${VERSION} -X main.Build=${BUILD}"
    if [ x"$?" == x"0" ]; then
		echo -e "build $OutPath$Target done,\033[0;33m ready upload... \033[0m"
	else
    	echo -e "build $OutPath$Target \033[0;31m failure \033[0m."
		exit 1
    fi

	scp $OutPath$Target shane@47.94.42.101:/home/shane/server/_bin/$Target

	if [ x"$?" == x"0" ]; then
		echo -e "publish $Target to environment[\033[0;36m test \033[0m]\033[0;32m finish \033[0m."
	else
		echo -e "publish $Target to environment[\033[0;36m test \033[0m]\033[0;31m failure \033[0m."
    fi
}

function do_online_env()
{
    echo -e "target:$Target\033[0;33m build... \033[0m"
    CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-w" -o $OutPath$Target main.$ExeName.go

    if [ x"$?" == x"0" ]; then
		echo -e "build $OutPath$Target done,\033[0;33m ready upload... \033[0m"
	else
    	echo -e "build $OutPath$Target \033[0;31m failure \033[0m."
		exit 1
    fi

	scp $OutPath$Target shane@106.13.135.168:/home/shane/server/$Target

	if [ x"$?" == x"0" ]; then
		echo -e "publish $Target to environment[\033[0;34m online \033[0m]\033[0;32m finish \033[0m."
	else
		echo -e "publish $Target to environment[\033[0;34m online \033[0m]\033[0;31m failure \033[0m."
    fi
}

function do_local_run()
{
    go build -o $OutPath$Target main.$ExeName.go
    if [ x"$?" == x"0" ]; then
		echo -e "build $OutPath$Target done,\033[0;33m ready start... \033[0m"
        $StartComment
	else
        echo -e "build $OutPath$Target \033[0m\033[0;31m failure \033[0m."
    fi
}

function do_local_build()
{
    go build -o $OutPath$Target main.$ExeName.go
    if [ x"$?" == x"0" ]; then
		echo -e "build $OutPath$Target done,\033[0;33m success \033[0m"
	else
        echo -e "build $OutPath$Target \033[0m\033[0;31m failure \033[0m."
    fi
}

case $1 in
    online)
    do_online_env;;
    test)
    do_test_env;;
    run)
    do_local_run;;
	build)
    do_local_build;;
    *)

esac

rm -f main.$ExeName.go

